var inter = null;
var cardStatus = false;
var cardIndex = 0;
var pages = 0;
$(function () {
    $('.newCenter-footer__wrap,#js-slide-operation').remove();
    var status = $("#status").val();
    if(status==1){
        //初始化时间
        initTime();
    }else{
        var _time = $("#examTime").val();
        var str = addHandleExamTime(_time);
        $("#timer").text(str);
    }
    var examRecordId = $("#examRecordId").val();
    //加载作业答题卡内容
    loadTaskCard(examRecordId);
    //加载第1页试题记录
    loadTaskQuestionList({
        examRecordId:examRecordId,
        status:status,
        pageNo:1,
        callback: function () {
            pages = parseInt($("#pages").val());
            $("#pages").remove();
            // 初始化轮播
            initCarousel();
            //处理第一道题的题型
            firstCarousel();
        }
    });

    //设置最大调试
    largeHeight();

    $('body').on('click', 'li[id^=li]', function() {//包含有子试题下的小试题切换显示
        $(this).addClass('active').siblings().removeClass('active');
        var id = $(this).attr('id').split('_')[1];
        $('#div_' + id).addClass('active').siblings().removeClass('active');
    }).on('click', '#finish', function () { //完成作业
        submitMemberTaskRecord(2);
    }).on('click','#saveDraft',function () {//保存草稿
        submitMemberTaskRecord(1);
    }).on('click', '.slide-tihao', function () { // 答题卡切换试题
        cardStatus = true;
        var index = $(this).data("index");//试题记录下标
        cardIndex = index-1;
        $("#carousel-professional").carousel(cardIndex);//滑动到指定试题
        $('.scantron-box').addClass('hide');//隐藏答题卡
    }).on('click', '.prev-slide', function () { // 上一题
        $("#carousel-professional").carousel('prev');
    }).on('click', '.next-slide', function () { // 下一题
        $("#carousel-professional").carousel('next');
    }).on("click", "#scantron", function () { // 答题卡
        $(".scantron-box").toggleClass("hide");
    }).on('ifChanged','input:radio,input:checkbox',function (event) {//选中单选、多选、判断

        var status = false;
        if(event.target.checked){
            status = true;
        }else{
            if(event.target.type !='radio'){
                status = true;
            }
        }
        if(status){
            saveQuestionRecord(this);
        }
    }).on('blur','input[data-answer]:text',function () {//填空题
        saveQuestionRecord(this);
    }).on('blur','textarea[data-answer]',function () {//简答题
        saveQuestionRecord(this);
    });


    /**
     * 保存试题记录
     * @param em 被操作的元素
     */
    function saveQuestionRecord(em) {
        var root = $($(em).parents('article.active')[0]);
        var currentId = root.data('id');//作业试题记录ID
        var saveId = getSaveId(currentId);
        $(".ic-answerCard-num-list").find("a[data-id="+currentId+"]").parent('li').addClass('ac-ok');
        _saveQuestionRecord(currentId,saveId);
    }

    //执行保存
    function _saveQuestionRecord(currentId,saveId,callback) {
        if(saveId > 0){
            var root = $($("article[data-id='"+saveId+"']")[0]);
            var userAnswer = getAnswerObj(root);//获取答案对象
            userAnswer = encodeURIComponent(JSON.stringify(userAnswer));//转码答案对象
            var examRecordId = $("#examRecordId").val();//考试记录ID
            var key = examRecordId+'-'+saveId+'-'+userAnswer;
            $("#key").val(key);
            saveData(key,examRecordId,saveId,userAnswer,function () {
                updateSaveData(saveId,currentId,callback);
            });
        }else{
            updateSaveData(saveId,currentId,callback);
        }
    }

    /**
     * 保存试卷
     * @param status 状态，1退出答题（未完成作业），2提交试题（完成作业作答）
     */
    function submitMemberTaskRecord(status) {
        //保存未提交的最后道作答试题
        var saveId = getSaveId(0);
        _saveQuestionRecord(0,saveId,function (){
            var examRecordId = $("#examRecordId").val();
            var examTime = $("#examTime").val();
            saveExamRecordData(examRecordId,status,examTime,function () {
                if(status==1){
                    window.location.href = baseloaction +'/web/uc/task/getClassesTaskList';
                }else{
                    window.location.href = baseloaction +'/web/uc/task/startTask?id='+examRecordId;
                }
            });
        });
    }

    /**
     * 初始化滑动
     */
    function initCarousel() {
        $("#carousel-professional").carousel({interval: false}).on('slid.bs.carousel', function (obj) { // 滚动完成
            var active = initPrevNext();
            var pageNo = active.data('no');//当前页码
            if(cardStatus==true){//答题卡切题
                loadTaskQuestionList({//加载上一页
                    examRecordId:examRecordId,
                    status:status,
                    pageNo: pageNo,
                    callback:function () {
                        $(".prev-slide").prop('disabled', active.prev('.changeless-box').length === 0);
                        cardStatus = false;
                        if(cardIndex !=0){
                            $("#carousel-professional>.carousel-inner>article").eq(cardIndex).addClass('active');
                            initPrevNext();
                            cardIndex = 0;
                        }
                    }
                });
            }else{//不是答题卡切题
                if(obj.direction=='right'){//上一道
                    var prevLen = active.prev('.changeless-box').length;
                    if(prevLen==0 && pageNo > 1){
                        loadTaskQuestionList({//加载上一页
                            examRecordId:examRecordId,
                            status:status,
                            pageNo: pageNo -1,
                            callback:function () {
                                $(".prev-slide").prop('disabled', active.prev('.changeless-box').length === 0);
                            }
                        });
                    }
                }else{//下一道
                    var nextLen = active.next('.changeless-box').length;
                    if(nextLen==0 && pages > pageNo){//加载下一页
                        loadTaskQuestionList({
                            examRecordId:examRecordId,
                            status:status,
                            pageNo: pageNo + 1,
                            callback:function () {
                                $(".next-slide").prop('disabled', active.next('.changeless-box').length === 0);
                            }
                        });
                    }
                }
            }
        });
    }

    /**
     * 处理第一个试题的滑动
     */
    function firstCarousel() {
        var active = $('.carousel-inner article:first-child').addClass("active");
        var templateName = active.data('name');
        $("#template-name-box").text(templateName);
    }

    /**
     * 初始化上一道、下一道、试题类型显示
     */
    function initPrevNext() {
        var active = $('.carousel-inner article.active');
        var templateName = active.data('name');
        $("#template-name-box").text(templateName);
        $(".next-slide").prop('disabled', active.next('.changeless-box').length === 0);
        $(".prev-slide").prop('disabled', active.prev('.changeless-box').length === 0);
        return active;
    }
});


/**
 * 初始化时间显示
 */
function initTime() {
    var examTime = parseInt($("#examTime").val());
    inter = setInterval(function () {
        examTime = parseInt($("#examTime").val());
        var _time = examTime + 1;
        var str = addHandleExamTime(_time);
        $("#timer").text(str);
        $("#examTime").val(_time);
    },1000);
}
/**
 * 处理时间，返回HH:mm:ss
 * @param _time 时间（单位/秒）
 */
function addHandleExamTime(_time) {
    var HH = parseInt(_time/(60*60));
    if(HH==0){
        HH = "00";
    }else{
        if(HH < 10){
            HH = "0"+HH;
        }
    }
    var mm = parseInt((_time % (60*60)) /60);
    if(mm==0){
        mm = "00";
    }else{
        if(mm < 10){
            mm = "0"+mm;
        }
    }
    var ss = parseInt(_time % (60*60) % 60);
    if(ss==0){
        ss = "00";
    }else{
        if(ss < 10){
            ss = "0"+ss;
        }
    }
    return HH+":"+mm+":"+ss;
}

/**
 * 设置最大调试
 */
function largeHeight() {
    var largeHeader = document.getElementById('uCenterMain'),
        height = window.innerHeight;
    largeHeader.style.height = (height - 50) + 'px';
}

window.onresize = function () {
    largeHeight()
};